package config

import (
	"fmt"
	"io/ioutil"

	"gopkg.in/yaml.v2"
)

type TemplateCfg struct {
	TemplateId string `yaml:"templateId"`
}

type ServerConfig struct {
	ListenAddr string      `yaml:"listenAddr"`
	Region     string      `yaml:"region"`
	AppId      string      `yaml:"appId"`
	SignName   string      `yaml:"signName"`
	SecretId   string      `yaml:"secretId"`
	SecretKey  string      `yaml:"secretKey"`
	RegSms     TemplateCfg `yaml:"regSms"`
	ResetSms   TemplateCfg `yaml:"resetSms"`
}

func ReadConfig(fileName string) (*ServerConfig, error) {
	data, err := ioutil.ReadFile(fileName)
	if err != nil {
		return nil, err
	}
	servCfg := &ServerConfig{}
	err = yaml.Unmarshal(data, servCfg)
	if err != nil {
		return nil, err
	}
	if servCfg.Region == "" {
		return nil, fmt.Errorf("miss region config")
	}
	if servCfg.AppId == "" {
		return nil, fmt.Errorf("miss appId config")
	}
	if servCfg.SignName == "" {
		return nil, fmt.Errorf("miss signName config")
	}
	if servCfg.SecretId == "" {
		return nil, fmt.Errorf("miss secretId config")
	}
	if servCfg.SecretKey == "" {
		return nil, fmt.Errorf("miss secretKey config")
	}

	if servCfg.RegSms.TemplateId == "" {
		return nil, fmt.Errorf("miss regSms.templateId config")
	}
	if servCfg.ResetSms.TemplateId == "" {
		return nil, fmt.Errorf("miss resetSms.templateId config")
	}
	return servCfg, nil
}
